<template>
  <div class="pay">
    <div class="pay-back">
      <span @click="back"></span>
    </div>
    <div class="pay-title">
      <p>感谢您的选择!</p>
      <p class="title-bold">我们会尽快送达!</p>
    </div>
    <div class="pay-list">
      <div class="list-title">
        <span>商品信息</span>
      </div>
      <div
        class="list-commodity"
        v-for="(item, index) in payShopbagData"
        :key="index"
      >
        <div class="cmdty-img">
          <img class="autoImg" :src="item.small_img" />
        </div>
        <div class="cmdty-name">
          <div class="trade-name">
            <span>{{ item.name }}</span>
          </div>
          <div class="cmdty-rules">
            <span>{{ item.rule }}</span>
          </div>
        </div>
        <div class="cmdty-price">
          <div class="price_pay">
            <span>&yen;{{ item.price }}</span>
          </div>
          <div class="count_pay">
            <span>x&nbsp;{{ item.count }}</span>
          </div>
        </div>
      </div>
      <van-divider
        :style="{
          color: '#f7f7f7',
          borderColor: '#666',
          padding: '0 16px',
          marginTop: '5px',
        }"
      />
      <div class="pay-total">
        <div class="total">
          <span>总计:</span>
        </div>
        <div class="price">
          <span>&yen;{{ proInfo.total }}</span>
        </div>
      </div>
    </div>

    <div class="pay-distribution">
      <div class="distribution-title">
        <span>配送信息</span>
      </div>
      <div class="distribution-user">
        <div class="username">
          <span class="point"></span>
          <span class="name-user">{{ currentAddress.name }}</span>
        </div>
        <div class="user-phone">
          <span>{{ currentAddress.tel }}</span>
        </div>
      </div>
      <div class="address">
        <div>
          <span
            >{{ currentAddress.province }}{{ currentAddress.city
            }}{{ currentAddress.county }}</span
          >
        </div>
        <div>
          <span>{{ currentAddress.addressDetail }}</span>
        </div>
      </div>
      <van-divider
        :style="{
          color: '#f7f7f7',
          borderColor: '#666',
          padding: '0 16px',
          margin: '10px 0 0',
        }"
      />
      <div class="pay-other" @click="otherAddress">
        <div class="other-address">
          <span>其他地址</span>
        </div>
        <div class="other-more">
          <van-icon name="arrow" size="20px" />
        </div>
      </div>
      <van-divider
        :style="{
          color: '#f7f7f7',
          borderColor: '#666',
          padding: '0 16px',
          margin: '0',
        }"
      />
      <div class="pay-service">
        <div class="service">
          <span>预计送达时间</span>
        </div>
        <div class="service-time">
          <span>51分钟</span>
        </div>
      </div>
    </div>
    <div class="pay-box">
      <van-divider
        :style="{
          color: '#f7f7f7',
          borderColor: '#666',
          padding: '0 16px',
          margin: '10px',
        }"
      />
      <div class="pay-button">
        <van-button block color="#21b276" round @click="pay"
          >立刻结算</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import "../assets/less/pay.less";
import { mapState, mapMutations } from "vuex";
export default {
  name: "Pay",
  data() {
    return {
      show: false,
      list: [],
      currentAddress: {},
      sids: [],
      payShopbagData: [],
      proInfo: {
        count: 0,
        total: 0,
      },
    };
  },
  computed: {
    ...mapState(["shopbagData"]),
  },
  created() {
    this.sids = this.$route.query.sids.split("-");
    this.getAddressListData();
    this.getShopbagDataByPay();
  },

  methods: {
    ...mapMutations(["loadShopbagCountChange"]),

    back() {
      this.$router.go(-1);
    },
    getAddressListData() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "GET",
        url: this.baseUrl + "/findAddress",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((res) => {
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 20000) {
            //添加address属性
            res.data.result.forEach((v) => {
              v.address = `${v.province}${v.city}${v.county}${v.addressDetail}`;
              v.isDefault = Boolean(v.isDefault);
              if (v.isDefault) {
                this.chosenAddressId = v.id;
                this.currentAddress = { ...v };
              }
            });

            this.list = res.data.result;
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    getShopbagDataByPay() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "GET",
        url: this.baseUrl + "/commitShopcart",
        params: {
          appkey: this.appkey,
          tokenString,
          sids: JSON.stringify(this.sids),
        },
      })
        .then((res) => {
          this.$toast.clear();
          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }
          if (res.data.code == 50000) {
            // if (res.data.result.length === 0) {
            //   return this.$router.push({ path: "/" });
            // }

            res.data.result.forEach((v) => {
              this.proInfo.count += v.count;
              this.proInfo.total += v.count * v.price;
            });
            this.payShopbagData = res.data.result;
            console.log(this.payShopbagData);
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },
    otherAddress() {
      this.$router.push({ name: "AddressList" });
    },
    pay() {
      if (!this.currentAddress.aid) {
        return this.$toast({
          message: "选择收货地址",
          forbidClick: true,
          duration: 3000,
        });
      }

      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      let data = {
        appkey: this.appkey,
        tokenString,
        sids: JSON.stringify(this.sids),
        phone: this.currentAddress.tel,
        address: this.currentAddress.address,
        receiver: this.currentAddress.name,
      };

      this.axios({
        //请求方式
        method: "POST",
        url: this.baseUrl + "/pay",
        data,
      })
        .then((res) => {
          // console.log("res pay ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 60000) {
            //修改vuex的购物袋数量
            this.loadShopbagCountChange(this.shopbagCount - this.sids.length);

            //跳转到订单组件
            this.$router.push({ name: "Order" });
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
  },
};
</script>